#include "pch.hpp"
#include "D3D11Texture.hpp"
#include "D3D11Exception.hpp"

using namespace Engine;
using namespace Engine::Video;




D3D11Texture::D3D11Texture(const notify_t& destroyedFn, const QByteArray& data, const ID3D11DevicePtr& device)
	: m_destroyedFn(destroyedFn)
	, m_texture(createTexture(data, device))
	, m_resourceView(createResourceView(m_texture, device))
{}
///////////////////////////////////////////////////////////////////////////////////////////////////

void D3D11Texture::post_create(ptr _this)
{
	m_this = _this;
}
///////////////////////////////////////////////////////////////////////////////////////////////////

D3D11Texture::~D3D11Texture()
{
	m_destroyedFn(m_this);
}
///////////////////////////////////////////////////////////////////////////////////////////////////




const ID3D11ShaderResourceViewPtr& D3D11Texture::view() const
{
	return m_resourceView;
}
///////////////////////////////////////////////////////////////////////////////////////////////////




ID3D11ResourcePtr D3D11Texture::createTexture(const QByteArray& data, const ID3D11DevicePtr& device)
{
	// Load the texture and initialize an ID3D11Texture2D object.
	ID3D11Resource* tex = NULL;
	D3DX11CreateTextureFromMemory(device.get(), data.constData(), data.size(), NULL, NULL, &tex, NULL );
	return ID3D11ResourcePtr(tex);
}
///////////////////////////////////////////////////////////////////////////////////////////////////

ID3D11ShaderResourceViewPtr D3D11Texture::createResourceView(const ID3D11Texture2DPtr& texture, const ID3D11DevicePtr& device)
{
	// Get a texture description to determine the texture
	// format of the loaded texture.
	D3D11_TEXTURE2D_DESC desc;
	texture->GetDesc(&desc);

	// Fill in the D3D11_SHADER_RESOURCE_VIEW_DESC structure.
	D3D11_SHADER_RESOURCE_VIEW_DESC srvDesc;
	ZeroMemory(&srvDesc, sizeof(srvDesc));
	srvDesc.Format = desc.Format;
	srvDesc.ViewDimension = D3D11_SRV_DIMENSION_TEXTURE2D;
	srvDesc.Texture2D.MostDetailedMip = 0;
	srvDesc.Texture2D.MipLevels       = desc.MipLevels;

	// Create the shader resource view.
	ID3D11ShaderResourceView* srView = NULL;
	D3D11_API(device->CreateShaderResourceView(texture.get(), &srvDesc, &srView));
	return ID3D11ShaderResourceViewPtr(srView);
}
///////////////////////////////////////////////////////////////////////////////////////////////////
